package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductUpdateDTO;
import cn.tedu.coolshark.pojo.dto.ProductDTO;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product/")
public class ProductController {
    @Autowired
    ProductMapper mapper;
    @RequestMapping("insert")
    public void insert(@RequestBody ProductDTO productDTO){
        System.out.println("productDTO = " + productDTO);
        Product product=new Product();
        BeanUtils.copyProperties(productDTO,product);
        product.setCreated(new Date());
        product.setViewCount(0);
        mapper.insert(product);
    }
    @RequestMapping("select")
    public List<ProductAdminVO> select(){
       return mapper.select();
    }
    @RequestMapping("deleteById")
    public void deleteById(int id){
        String url = mapper.selectUrlById(id);
        new File(dirPath+url).delete();
        mapper.deleteById(id);
    }
    @RequestMapping("selectById")
    public ProductUpdateVO selectById(int id){
        return mapper.selectById(id);
    }
    @Value("${imagesPath}")
    private String dirPath;
    @RequestMapping("update")
    public void update(@RequestBody ProductUpdateDTO productUpdateDTO){
        /*增改需要将dto换成entity*/
        String url=mapper.selectUrlById(productUpdateDTO.getId());
        if(!url.equals(productUpdateDTO.getUrl())){
            new File(dirPath+url).delete();
        }

        Product product=new Product();
        BeanUtils.copyProperties(productUpdateDTO,product);
        mapper.update(product);
    }
    @RequestMapping("top")
    public List<ProductTopVO> top(){
        return mapper.selectTop();
    }
    @RequestMapping("index")
    public List<ProductIndexVO> index(){
        return mapper.selectIndex();
    }
    @RequestMapping("detail")
    public ProductDetailVO detailById(int id, HttpSession session){
        String info=(String)session.getAttribute("view"+id);
        if(info==null){
            mapper.updateViewCountById(id);
            session.setAttribute("view"+id,"visited");
        }

        return mapper.detailById(id);
    }
    @RequestMapping("category")
    public List<ProductIndexVO> category(int id){
        return mapper.selectByCategoryId(id);
    }
    @RequestMapping("search")
    public List<ProductIndexVO> search(String wd){
        return mapper.selectByWd(wd);
    }

}
